#define _CRT_SECURE_NO_WARNINGS 1

#include"TripleTable.h"

void CreateMat(TSMatrix* qt, ElemType arr[N][N])
{
	qt->rows = N;
	qt->cols = N;
	qt->nums = 0;
	int i = 0;
	int j = 0;
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < N; j++)
		{
			if (arr[i][j] != 0)
			{
				qt->data[qt->nums].r = i;
				qt->data[qt->nums].c = j;
				qt->data[qt->nums].d = arr[i][j];
				qt->nums++;
			}
		}
	}
}

void DispMat(TSMatrix qt)
{
	if (qt.nums <= 0)
	{
		return;
	}
	printf("\t%d\t%d\t%d\n", qt.rows, qt.cols, qt.nums);
	printf("----------------------------\n");
	int i = 0;
	for (i = 0; i < qt.nums; i++)
	{
		printf("\t%d\t%d\t%d\n", qt.data[i].r, qt.data[i].c, qt.data[i].d);
	}
}

void TranMat(TSMatrix qt1, TSMatrix* qt2)
{
	int i = 0;
	int j = 0;
	int k = 0;
	qt2->rows = qt1.cols;
	qt2->cols = qt1.rows;
	qt2->nums = qt1.nums;
	if (qt1.nums != 0)
	{
		for (i = 0; i < qt1.cols; i++)
		{
			for (j = 0; j < qt1.nums; j++)
			{
				if (qt1.data[j].c == i)
				{
					qt2->data[k].r = qt1.data[j].c;
					qt2->data[k].c = qt1.data[j].r;
					qt2->data[k].d = qt1.data[j].d;
					k++;
				}
			}
		}
	}
}

bool MatAdd(TSMatrix a, TSMatrix b, TSMatrix* c)
{
	if (a.rows != b.rows || a.cols != b.cols)
	{
		return false;
	}
	int i = 0;
	int j = 0;
	int k = 0;
	ElemType value = 0;
	c->cols = a.cols;
	c->rows = a.rows;
	while (i < a.nums && j < b.nums)
	{
		if (a.data[i].r == b.data[j].r)
		{
			if (a.data[i].c < b.data[j].c)
			{
				c->data[k].r = a.data[i].r;
				c->data[k].c = a.data[i].c;
				c->data[k].d = a.data[i].d;
				k++;
				i++;
			}
			else if (a.data[i].c > b.data[j].c)
			{
				c->data[k].r = b.data[j].r;
				c->data[k].c = b.data[j].c;
				c->data[k].d = b.data[j].d;
				k++;
				j++;
			}
			else
			{
				value = a.data[i].d + b.data[j].d;
				if (value != 0)
				{
					c->data[k].r = a.data[i].r;
					c->data[k].c = a.data[i].c;
					c->data[k].d = value;
					k++;
				}
				i++;
				j++;
			}
		}
		else if (a.data[i].r < b.data[j].r)
		{
			c->data[k].r = a.data[i].r;
			c->data[k].c = a.data[i].c;
			c->data[k].d = a.data[i].d;
			k++;
			i++;
		}
		else
		{
			c->data[k].r = b.data[j].r;
			c->data[k].c = b.data[j].c;
			c->data[k].d = b.data[j].d;
			k++;
			j++;
		}
		c->nums = k;
	}
	return true;
}

int GetValue(TSMatrix qt, int i, int j)
{
	int k = 0;
	while (k < qt.nums && (qt.data[k].r != i || qt.data[k].c != j))
	{
		k++;
	}
	if (k < qt.nums)
	{
		return qt.data[k].d;
	}
	else
	{
		return 0;
	}
}

bool MatMul(TSMatrix a, TSMatrix b, TSMatrix* c)
{
	if (a.cols != b.rows)
	{
		return false;
	}
	int i = 0;
	int j = 0;
	int k = 0;
	int n = 0;
	ElemType value = 0;
	for (i = 0; i < a.rows; i++)
	{
		for (j = 0; j < b.cols; j++)
		{
			value = 0;
			for (k = 0; k < a.cols; k++)
			{
				value = value + GetValue(a, i, k) * GetValue(b, k, j);
			}
			if (value != 0)
			{
				c->data[n].r = i;
				c->data[n].c = j;
				c->data[n].d = value;
				n++;
			}
		}
	}
	c->rows = a.rows;
	c->cols = b.cols;
	c->nums = n;
	return true;
}